﻿using NoteHelper.IBusiness;
using NoteHelper.Utils;
using System.Collections.Generic;
using System.Data;
using Unity;
using System;
using NoteHelper.BaseControl;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace NoteHelper
{
    public partial class ArticleBaseForm : WeifenLuo.WinFormsUI.Docking.DockContent
    {
        private IArticleManager articleManager;
        private IArticleTypeManager articleTypeManager;
        private const string TblNote = "Notes";
        private const string TblAttr = "Attributes";
        private const string TblArticle = "Article";
        private log4net.ILog logger;
        private DataSet _ds;
        private int _objectId;
        DevAge.ComponentModel.BoundDataView mBoundList;

        public ArticleBaseForm(int noteId)
        {
            InitializeComponent();

            logger = log4net.LogManager.GetLogger(this.GetType());
            var container = UnityHelper.GetContainer();
            articleManager = container.Resolve<IArticleManager>();
            articleTypeManager = container.Resolve<IArticleTypeManager>();

            _objectId = noteId;
            LoadDataToForm();
        }

        private void LoadDataToForm()
        {
            this.Text = $"Note{_objectId}";
            _ds = articleManager.GetArticle(_objectId);
            lblCreateTime.Text = string.Format("{0:yyyy-MM-dd hh:mm:ss}", _ds.Tables[TblArticle].Rows[0]["CreateTime"]);
            lblLastUpdateTime.Text = string.Format("{0:yyyy-MM-dd hh:mm:ss}", _ds.Tables[TblArticle].Rows[0]["LastUpdateTime"]);
            tbxDescription.Text = _ds.Tables[TblArticle].Rows[0]["Description"].ToString();
            textBox1.Text = _ds.Tables[TblArticle].Rows[0]["FileUrl"].ToString();

            var lst = new List<string>();
            foreach (DataRow row in _ds.Tables[TblAttr].Rows)
            {
                lst.Add(row["ChName"].ToString());
            }
            attributesList1.Attributes = lst;

            dataGrid1.FixedColumns = 1;
            dataGrid1.FixedRows = 1;
            dataGrid1.Columns.Clear();

            DataTable orders = _ds.Tables[TblNote];
            mBoundList = new DevAge.ComponentModel.BoundDataView(orders.DefaultView);
            mBoundList.AllowNew = true;
            mBoundList.AllowEdit = true;
            mBoundList.AllowDelete = true;

            //Create default columns
            CreateColumns();
            dataGrid1.DataSource = mBoundList;
        }

        private void CreateColumns()
        {
            //Create columns
            SourceGrid.DataGridColumn gridColumn;

            gridColumn = dataGrid1.Columns.Add("ObjectID", "ID", typeof(int));
            gridColumn.DataCell.Editor = null;
            gridColumn.Width = 50;
            gridColumn = dataGrid1.Columns.Add("CreateTime", "创建时间", typeof(DateTime));
            gridColumn.DataCell.Editor = null;
            gridColumn.Width = 120;
            gridColumn = dataGrid1.Columns.Add("Description", "描述", typeof(string));
            gridColumn.Width = 480;
                        
            #region ==== 删除 ====
            SourceGrid.Cells.Views.Link viewLink = new SourceGrid.Cells.Views.Link();
            viewLink.ImageAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            viewLink.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;

            var linkButton = new SourceGrid.Cells.Link();
            linkButton.Value = "删除";
            gridColumn = dataGrid1.Columns.Add(null, "操作", linkButton);
            gridColumn.DataCell.AddController(new LinkClickDelete());
            gridColumn.DataCell.View = viewLink;
            #endregion

            #region ==== 详细 ====
            SourceGrid.Cells.Views.Link viewLink2 = new SourceGrid.Cells.Views.Link();
            viewLink2.ImageAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            viewLink2.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;

            var displayButton = new SourceGrid.Cells.Link();
            displayButton.Value = "显示";
            gridColumn = dataGrid1.Columns.Add(null, "详细", displayButton);

            SourceGrid.Cells.Controllers.Button linkEvents = new SourceGrid.Cells.Controllers.Button();
            linkEvents.Executed += new EventHandler(linkEvents_Executed);
            gridColumn.DataCell.AddController(linkEvents);
            gridColumn.DataCell.View = viewLink2;
            #endregion
        }

        private void linkEvents_Executed(object sender, EventArgs e)
        {
            var context = (SourceGrid.CellContext)sender;
            // context.Position, context.Position.Row, context.Position.Column
            var datagrid = (SourceGrid.DataGrid)context.Grid;
            if (context.Position.Row - 1 < mBoundList.DataTable.Rows.Count)
            {
                var row = mBoundList.DataTable.Rows[context.Position.Row - 1];
                var noteForm = new NoteForm();
                noteForm.Note = row["Description"].ToString();
                if (noteForm.ShowDialog() == DialogResult.Yes)
                {
                    row["Description"] = noteForm.Note;
                }
                noteForm.Dispose();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 删除附件
            var file = Path.Combine(BasePath, FilePath);
            if (File.Exists(file))
            {
                if (AlterMsg.Confirm("您确定要删除附件？"))
                {
                    File.Delete(file);
                    FilePath = "";
                    _ds.Tables[TblArticle].Rows[0]["FileUrl"] = FilePath;
                    articleManager.SaveOrUpdateArticle(_ds, _objectId);
                    AlterMsg.Info("删除成功！");
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 打开附件
            var file = Path.Combine(BasePath, FilePath);
            if (File.Exists(file))
            {
                System.Diagnostics.Process.Start(file); //打开此文件。
            }
        }

        public bool SaveAll()
        {
            this.tbxDescription.Focus(); // 保证grid失去焦点，确保_ds为最新状态
            if (attributesList1.Attributes.Count == 0)
            {
                AlterMsg.Info("标签不能为空！");
                return false;
            }

            _ds.Tables[TblArticle].Rows[0]["Description"] = tbxDescription.Text.Trim();
            _ds.Tables[TblArticle].Rows[0]["FileUrl"] = textBox1.Text;
            DataTable orders = _ds.Tables[TblNote];
            foreach (DataRow row in orders.Rows)
            {
                if (row["ObjectID"] == null || row["ObjectID"] == DBNull.Value)
                    row["ObjectID"] = 0;
            }

            // 删除
            var newList = attributesList1.Attributes;
            int count = _ds.Tables[TblAttr].Rows.Count;
            for (int i = count - 1; i >=0; i--)
            {
                var name = _ds.Tables[TblAttr].Rows[i]["ChName"].ToString();
                if (!newList.Contains(name))
                {
                    _ds.Tables[TblAttr].Rows.RemoveAt(i);
                }
            }
            // 新增
            foreach (string typeName in newList)
            {
                var whereSql = string.Format("ChName='{0}'", typeName);
                count = (int)_ds.Tables[TblAttr].Compute("Count(ChName)", whereSql);
                if (count == 0)
                {
                    var row = _ds.Tables[TblAttr].NewRow();
                    row["ObjectID"] = 0;
                    row["ChName"] = typeName;
                    _ds.Tables[TblAttr].Rows.Add(row);
                }
            }
            if (logger.IsDebugEnabled)
                logger.Debug(ControlExt.DisplayCurrentContext(_ds));

            int id = articleManager.SaveOrUpdateArticle(_ds, _objectId);
            var msg = _objectId > 0 ? "修改成功" : "添加成功";
            _objectId = id;
            LoadDataToForm();
            AlterMsg.Info(msg);
            return true;
        }        

        private string BasePath
        {
            get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files"); }
        }

        private string FilePath
        {
            get { return textBox1.Text; }
            set { textBox1.Text = value; }
        }

        private void btnFileUpload_Click(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = BasePath,
                Filter = "所有文件|*.*",
                RestoreDirectory = true,
                FilterIndex = 1
            };
            if (openFileDialog.ShowDialog() != DialogResult.OK) return;

            string fName = openFileDialog.FileName;
            if (string.IsNullOrEmpty(fName)) return;

            // 一年一个文件夹
            string folder = string.Format("Doc{0:yyyy}", DateTime.Today);
            string path = Path.Combine(BasePath, folder);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var fileName = Path.GetFileName(fName);
            FilePath = folder + "\\" + fileName;
            path = Path.Combine(path, fileName);
            File.Copy(fName, path, true);

            // 文件上传，实际就覆盖了原文件，所以需要删除原文件，并修改数据库记录！
            var entity = articleManager.Get(_objectId);
            if (entity != null)
            {
                var oldFile = Path.Combine(BasePath, entity.FileUrl);
                if (File.Exists(oldFile))
                {
                    File.Delete(oldFile);
                }
                entity.FileUrl = FilePath;
                articleManager.Update(entity);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            SaveAll();
        }
    }
}